package servlet;

import domain.sales;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 从request中获取搜索参数year和month的值
        String year = req.getParameter("year");
        String month = req.getParameter("month");

        //调用模型层sales.java中的相关业务方法search，获取销售数量列表ps；
        List<sales> ps =new ArrayList<sales>();

        // 调用sales类的search方法，得到产品列表ps
        ps = sales.search("year","month"); // sales类中的search方法返回查询到的列表

        // 准备以CSV文件形式下载
        String fileName = year + "年" + month + "月销售榜单.csv";
        resp.setContentType("text/csv"); // 设置正确的响应类型为CSV
        resp.setCharacterEncoding("UTF-8"); // 确保CSV文件内容的编码一致

        // 正确设置Content-Disposition头，确保文件名正确显示且避免中文乱码
        resp.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GBK"),"iso8859-1"));

        try (PrintWriter out = resp.getWriter()) {
            // 写入CSV标题行
            out.println("商品名称,销售数量");

            // 遍历销售列表并输出到CSV
            for (int i = 0; i < ps.size(); i++) {
                sales arr=ps.get(i);
                out.println(arr.getName()+","+arr.getBuynum());
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            // 异常处理
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        doGet(req, resp);
    }

}
